import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../models/user.dart';

class StorageService {
  static const String _userKey = 'user_info';
  static const String _tokenKey = 'auth_token';
  
  // 安全存储实例，用于存储敏感信息如token
  final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();

  // 保存用户信息（除token外）
  Future<void> saveUserInfo(User user) async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = user.toJson();
    // 不在SharedPreferences中存储token
    userJson.remove('token');
    await prefs.setString(_userKey, jsonEncode(userJson));
    
    // 单独保存token到安全存储
    await _secureStorage.write(key: _tokenKey, value: user.token);
  }

  // 获取用户信息
  Future<User?> getUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    final userString = prefs.getString(_userKey);
    
    if (userString == null) {
      return null;
    }
    
    final userJson = jsonDecode(userString) as Map<String, dynamic>;
    
    // 从安全存储获取token
    final token = await _secureStorage.read(key: _tokenKey);
    if (token != null) {
      userJson['token'] = token;
    }
    
    return User.fromJson(userJson);
  }

  // 清除用户信息
  Future<void> clearUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_userKey);
    await _secureStorage.delete(key: _tokenKey);
  }

  // 检查用户是否已登录
  Future<bool> isLoggedIn() async {
    final token = await _secureStorage.read(key: _tokenKey);
    return token != null && token.isNotEmpty;
  }
}